package com.ueboot.weishop.api.configure;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ueboot.weishop.service.activity.ActivityService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;

import java.util.ArrayList;
import java.util.List;

/**
 * @author yangkui
 * reids 相关配置类
 */
@Slf4j
@Configuration
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 6000,redisNamespace="weishop")
public class ApiRedisConfig extends CachingConfigurerSupport {
    /**
     * spring cache注解支持。
     * @param redisTemplate
     * @return
     */
    @Bean
    public CacheManager cacheManager(
            @SuppressWarnings("rawtypes") RedisTemplate redisTemplate) {
        RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
        List<String> cacheNames = new ArrayList<String>();
        //定义缓存名称，使用是可以指定名称用于区分不同的缓存数据
        cacheNames.add("default");
        cacheNames.add("systemCache");
        cacheNames.add("springCacheManager");
        cacheNames.add("activity");
        cacheNames.add("activityAttr");
        cacheNames.add("goodsInfo");
        cacheNames.add("provinceCityDealer");
        cacheNames.add("customer");
        cacheNames.add("cusgroup");
        cacheNames.add("oilvin");
        cacheNames.add("orders");
        cacheManager.setCacheNames(cacheNames);
        return cacheManager;
    }

    /**
     * reids key 失效时的通知，如果需要注入其他service接口，直接在方法里面注入
     * @param connectionFactory
     * @return
     */
    @Bean
    RedisMessageListenerContainer keyExpirationListenerContainer(RedisConnectionFactory connectionFactory, ActivityService activityService) {

        RedisMessageListenerContainer listenerContainer = new RedisMessageListenerContainer();
        listenerContainer.setConnectionFactory(connectionFactory);

        listenerContainer.addMessageListener((message, pattern) -> {
            activityService.rollbackStock(new String(message.getBody()));

            // System.out.println("接收到失效通知："+message.toString());

        }, new PatternTopic("__keyevent@*__:expired"));

        return listenerContainer;
    }


} 